# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models, tools, _

from ..nc_api.odoo_nc import OdooNc


class Company(models.Model):
    _inherit = "res.company"

    ref = fields.Char(related="partner_id.ref")

    def write(self, vals):
        if 'ref' in vals:
            self.partner_id.ref = vals['ref']
            del vals['ref']

        return super().write(vals)


class NcOdsSaleOrder(models.Model):
    _name = "fp.nc.ods.sale.order"
    _description = "NC Ods Sales Order"
    # _order = 'date_order desc, id desc'
    # _check_company_auto = True

    # 通过 计算明细行 获得 折扣单/纯负数单

    ods_order_id = fields.Many2one('fp.ods.sale.order', 'Ods Order')
    name = fields.Char('NC PK')
    invoice_num = fields.Char('NC发票号')

    # 暂存 数据 备查. 这两个字段 作废 todo
    biz_type = fields.Char(string="类型", default='sale')
    api_status = fields.Char(string="api状态")

    # biz_type = fields.Selection(selection=[
    #     ('sale', '销售'),  # 销售
    #     ('refund', '退货'),  # 退货
    #     ('plus_neg', '正负行'),  # 正负行
    #     ('discount', '折扣'),  # 折扣
    # ], string="类型", default='sale')

    # api_status = fields.Selection(selection=[
    #     ('confirm', 'confirm'),  # 确认
    #     ('cancel', 'cancel'),  # 取消
    # ], string="api状态")

    state = fields.Selection([
        ('draft', 'Draft'),
        ('done', 'Done'),
        ('error', 'Error'),
    ], string='Status', readonly=True, copy=False, index=True, default='draft')

    company_code = fields.Char('公司代码')
    company_name = fields.Char('公司名称')

    user_phone = fields.Char('User Phone')

    partner_code = fields.Char('客户代码')
    partner_name = fields.Char('客户名称')

    amount_total = fields.Float('含税金额')
    note = fields.Text()

    # 暂存 数据 备查
    api_jsondata = fields.Text()

    line_ids = fields.One2many(
        'fp.nc.ods.sale.order.line', 'order_id', string='Order Lines')

    @api.model
    @api.returns('self', lambda value: value.ids)
    def import_create_for_nc(self, vals_list):
        odoonc = OdooNc()
        records1 = odoonc.after_read(vals_list)
        records = []
        for one in records1:
            lines = one['line_ids']
            lines2 = [(0, False,  ln) for ln in lines]
            one['line_ids'] = lines2
            records.append(one)
        new_result = self.create(records)
        new_result.load_to_model()

        return new_result

    def _load_partner(self):
        nc_customer = self.env['fp.nc.ods.customer']

        customers_values = {}
        for order in self:
            partner_code = order.partner_code
            old = nc_customer.search([('code', '=', partner_code)])

            if old:
                nc_customer = nc_customer | old
            else:
                if not customers_values.get(partner_code):
                    customers_values[partner_code] = {
                        'name': order.partner_name,
                        'code': order.partner_code,
                    }

        if customers_values:
            nc_customer2 = nc_customer.import_create_for_nc(
                list(customers_values.values()))

            nc_customer = nc_customer | nc_customer2

        return nc_customer._load_to_ods()

    @api.returns('self', lambda value: value.ids)
    def load_to_model(self):
        # 处理 客户 导入
        self._load_partner()

        # 处理 所有的 明细行上的 产品 导入
        self.mapped('line_ids')._load_product()

        # 然后 再 导入 order. 其中  orderline 的 product 只做  look 不能生成
        return self._load_to_ods()

    def _load_to_ods(self):
        # 1. look up。不能自动生成
        # 2. if has ods and isnot draft then set me no finished
        # 3  else set me finished

        ods_order = self.env['fp.ods.sale.order']

        for order in self:
            ods_order_id = self.env['fp.ods.sale.order'].search(
                [('client_order_ref', '=', order.name)], limit=1)
            if ods_order_id:
                if ods_order_id.state != 'draft':
                    order.state = 'error'
                    continue

            company_id = self.env['res.company'].search(
                [('partner_id.ref', '=', order.company_code)], limit=1)

            partner_id = self.env['fp.biz.partner'].search(
                [('code', '=', order.partner_code)], limit=1)

            user_id = order.user_phone and self.env['res.users'].search(
                [('phone', '=', order.user_phone)], limit=1) or self.env['res.users']

            vals = {
                'client_order_ref': order.name,
                'invoice_num': order.invoice_num,
                'biz_type': order.biz_type,
                'api_status': order.api_status,

                'company_id': company_id.id,
                'company_code': order.company_code,
                'company_name': order.company_name,

                'user_id': user_id.id,
                'user_phone': order.user_phone,

                'partner_id': partner_id.id,
                'partner_code': order.partner_code,
                'partner_name': order.partner_name,

                'amount_total': order.amount_total,
                'line_ids': order.line_ids._tuples_for_load_to_ods(ods_order_id)
            }

            if ods_order_id:
                ods_order_id.write(vals)

            else:
                ods_order_id = ods_order_id.create(vals)

            ods_order = ods_order | ods_order_id

            order.ods_order_id = ods_order_id
            order.state = 'done'

            for line in order.line_ids:
                ods_line_id = self.env['fp.ods.sale.order.line'].search(
                    [('client_line_ref', '=', line.line_pk),
                     ('id', 'in', ods_order_id.line_ids.ids)], limit=1)

                line.ods_line_id = ods_line_id

        return ods_order


class NcOdsSaleOrderLine(models.Model):
    _name = "fp.nc.ods.sale.order.line"
    _description = "NC ODS Sales Order Line"
    # _order = 'date_order desc, id desc'
    # _check_company_auto = True

    order_id = fields.Many2one(
        'fp.nc.ods.sale.order', string='Order Reference',
        required=True, ondelete='cascade', index=True, copy=False)

    ods_line_id = fields.Many2one('fp.ods.sale.order.line', 'Ods Line')

    line_pk = fields.Char('NC PK')
    order_num = fields.Char('NC订单号')
    logistics_num = fields.Char('配载号')

    name = fields.Text(string='Name', required=True)
    note = fields.Text(string='Description', required=True)
    sequence = fields.Integer(string='Sequence', default=10)

    vat_product_code = fields.Char(string='税收商品编码',)
    vat_product_name = fields.Char(string='税收商品名称')

    product_code = fields.Char(string='商品编码')
    product_name = fields.Char(string='商品名称')
    product_spec = fields.Char(string='规格型号',)
    product_uom = fields.Char(string='单位',)

    product_lot = fields.Char(string='批号')

    tax_ratio = fields.Float(string='tax_ratio',)

    quantity = fields.Float(string='Quantity', required=True, default=1.0)
    price_unit = fields.Float('Unit Price', required=True, default=0.0)

    def _load_product(self):
        nc_product = self.env['fp.nc.ods.product']
        products_values = {}
        for line in self:
            product_code = line.product_code
            old = nc_product.search(
                [('code', '=', product_code)])

            if old:
                nc_product = nc_product | old
            else:
                if not products_values.get(product_code):
                    products_values[product_code] = {
                        # 'company_code': line.order_id.company_code,
                        # 'company_name': line.order_id.company_name,
                        'name': line.product_name,
                        'code': line.product_code,
                        'spec': line.product_spec,
                        'uom': line.product_uom,
                        'vat_product_code': line.vat_product_code,
                        'vat_product_name': line.vat_product_name,
                        'tax_ratio': line.tax_ratio,
                        'price_unit': line.price_unit,
                    }

        if products_values:
            nc_product2 = nc_product.import_create_for_nc(
                list(products_values.values()))

            nc_product = nc_product | nc_product2

        return nc_product._load_to_ods()

    def _tuples_for_load_to_ods(self, ods_order_id):
        tuples_del = [(2,  ln.id, False) for ln in ods_order_id.line_ids
                      if ln.client_line_ref not in self.mapped('line_pk')]

        tuples = []
        for line in self:

            # product_id = self.env['fp.product'].search(
            #     [('code', '=', line.product_code)], limit=1)

            product_id = self.env['fp.product'].search_by_code(
                line.product_code)

            vals = {
                # 'order_id': ods_order_id.id,
                'client_line_ref': line.line_pk,
                'order_num': line.order_num,
                'logistics_num': line.logistics_num,
                'product_lot': line.product_lot,

                'name': line.name,
                'note': line.note,
                'sequence': line.sequence,
                'product_id': product_id.id,
                'tax_ratio': line.tax_ratio,
                'quantity': line.quantity,
                'price_unit': line.price_unit,
            }

            ods_line_id = self.env['fp.ods.sale.order.line'].search(
                [('client_line_ref', '=', line.line_pk),
                 ('id', 'in', ods_order_id.line_ids.ids)], limit=1)

            if ods_line_id:
                tuples.append((1, ods_line_id.id, vals))
            else:
                tuples.append((0, False, vals))

        return tuples_del + tuples
